package com.lh_travel.lohas.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lh_travel.lohas.R;
import com.lh_travel.lohas.activity.user.AboutLohasActivity;
import com.lh_travel.lohas.activity.user.AccountActivity;
import com.lh_travel.lohas.activity.user.CollectionActivity;
import com.lh_travel.lohas.activity.user.DestActivity;
import com.lh_travel.lohas.activity.user.EmpActivity;
import com.lh_travel.lohas.activity.user.FeedbackActivity;
import com.lh_travel.lohas.activity.user.LanActivity;
import com.lh_travel.lohas.activity.user.OrderActivity;
import com.lh_travel.lohas.activity.user.QuestionListActivity;
import com.lh_travel.lohas.activity.user.SharedActivity;
import com.lh_travel.lohas.activity.user.UserInfoActivity;
import com.lh_travel.lohas.adapter.CommonAdapter;
import com.lh_travel.lohas.adapter.ViewHolder;
import com.lh_travel.lohas.base.UnLazyBasefragment;
import com.lh_travel.lohas.base.api;
import com.lh_travel.lohas.dialogFragment.progressDialogFragment;
import com.lh_travel.lohas.domain.Comment;
import com.lh_travel.lohas.domain.HomeSec;
import com.lh_travel.lohas.domain.UserBean;
import com.lh_travel.lohas.domain.respon;
import com.lh_travel.lohas.interfaces.ContentChange;
import com.lh_travel.lohas.interfaces.PermissionListener;
import com.lh_travel.lohas.utils.DataCleanManager;
import com.lh_travel.lohas.utils.Preferences;
import com.lh_travel.lohas.widget.CircleImageView;
import com.squareup.picasso.Picasso;
import com.tamic.novate.Throwable;
import com.tamic.novate.callback.RxGenericsCallback;
import com.tamic.novate.callback.RxResultCallback;
import com.tamic.novate.callback.RxStringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * Created by aaron on 2018/6/6.
 */

public class HomeMyFragment extends UnLazyBasefragment {

    private ListView lv_my;
    private ArrayList<HomeSec> xmlList;
    private DrawerLayout drawer_layout;
    private ImageButton btn_setting;
    private ListView lv_draw_content;
    private ArrayList<String> draw_list;
    private ContentChange iChange;
    private Button btn_send;
    private Button btn_confirm;
    private EditText ed_tel, ed_pwd;
    private TextInputLayout til_tel;
    private progressDialogFragment loadingFragment;
    boolean isResumed;
    private boolean login;
    private myCountTimer timer;
    private CircleImageView cimg_avater;
    private CircleImageView cimg_draw_avater;
    private TextView tv_name;
    private TextView tv_sign;
    private TextView tv_draw_name;
    private TextView tv_draw_sign;
    private UserBean userBean;
    private TextView tv_vesion;
    private ImageView img_login_wechat;
    private ImageView img_login_qq;
    private String type;
    private RelativeLayout rl_head;
    private TextView tv_agreement;

    public HomeMyFragment() {
    }

    @SuppressLint("ValidFragment")
    public HomeMyFragment(ContentChange iChange) {

        this.iChange = iChange;
    }

    @Override
    protected int getLayoutId() {

        userBean = mApp.getBeanPrefernce(Preferences.LOCAL.USERLOGIN);

        login = (userBean != null ? true : false);

        return login ? R.layout.fragment_home_my : R.layout.fragment_log_in;
    }

    @Override
    protected void findView() {

        if (login) {

            lv_my = findViewByID(R.id.lv_my);
            drawer_layout = findViewByID(R.id.drawer_layout);
            btn_setting = findViewByID(R.id.btn_setting);
            lv_draw_content = findViewByID(R.id.lv_draw_content);

            cimg_avater = findViewByID(R.id.cimg_avater);
            tv_name = findViewByID(R.id.tv_name);
            tv_sign = findViewByID(R.id.tv_sign);

            cimg_draw_avater = findViewByID(R.id.cimg_draw_avater);
            tv_draw_name = findViewByID(R.id.tv_draw_name);
            tv_draw_sign = findViewByID(R.id.tv_draw_sign);

            tv_vesion = findViewByID(R.id.tv_vesion);
            rl_head = findViewByID(R.id.rl_head);

            btn_setting.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    drawer_layout.openDrawer(Gravity.RIGHT);
                }
            });

            rl_head.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = new Intent(mContext, UserInfoActivity.class);

                    startActivity(intent);
                }
            });

        } else {

            btn_confirm = findViewByID(R.id.btn_confirm);
            btn_send = findViewByID(R.id.btn_send);
            ed_tel = findViewByID(R.id.ed_tel);
            ed_pwd = findViewByID(R.id.ed_pwd);
            til_tel = findViewByID(R.id.til_tel);
            tv_agreement = findViewByID(R.id.tv_agreement);

            img_login_qq = findViewByID(R.id.img_login_qq);
            img_login_wechat = findViewByID(R.id.img_login_wechat);

            btn_confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (ed_tel.getText().toString().trim().length() < 11) {

                        showMessage("请输入正确的手机号");

                    } else if (ed_pwd.getText().toString().trim().length() == 0) {

                        showMessage("请输入正确的验证码");

                    } else {

                        showViewLoad();
                        new api(mContext).login(ed_tel.getText().toString().trim(), ed_pwd.getText().toString().trim(), loginCallBack);

                    }

                }
            });

            btn_send.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (ed_tel.getText().toString().trim().length() < 11) {

                        showMessage("请输入正确的手机号");

                    } else {

                        new api(mContext).sendCode(ed_tel.getText().toString().trim(), "login", new RxStringCallback() {
                            @Override
                            public void onNext(Object tag, String response) {
                                respon result = new Gson().fromJson(response, new TypeToken<respon>() {
                                }.getType());

                                if (result.code.equals("200")) {

                                    timer = new myCountTimer(60000, 1000, btn_send);
                                    timer.start();

                                    showMessage("验证码以发送到您手机上");

                                } else {

                                    showMessage("失败");

                                }
                            }

                            @Override
                            public void onError(Object tag, Throwable e) {

                            }

                            @Override
                            public void onCancel(Object tag, Throwable e) {

                            }
                        });
                    }
                }
            });

            img_login_qq.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    showViewLoad();
                    type = "1";
                    mApp.setPreference(Preferences.LOCAL.LOGINTYPE, "2");
                    login_third(QQ.NAME);
                }
            });

            img_login_wechat.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    showViewLoad();
                    type = "2";
                    mApp.setPreference(Preferences.LOCAL.LOGINTYPE, "3");
                    login_third(Wechat.NAME);
                }
            });

            tv_agreement.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = new Intent(mContext, DestActivity.class);

                    startActivity(intent);

                }
            });
        }
    }

    private void login_third(String name) {
        Platform plat = ShareSDK.getPlatform(name);
        plat.removeAccount(true); //移除授权状态和本地缓存，下次授权会重新授权
        plat.SSOSetting(false); //SSO授权，传false默认是客户端授权，没有客户端授权或者不支持客户端授权会跳web授权
        plat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(final Platform platform, int i, HashMap<String, Object> hashMap) {

                new api(mContext).loginThird(platform.getDb().getUserId(), type, platform.getDb().getUserName(),
                        platform.getDb().getUserIcon(), "", "", "", new RxResultCallback<UserBean>() {
                            @Override
                            public void onNext(Object tag, int code, String message, UserBean response) {

                                if (code == 200) {

                                    showMessage(message);
                                    dismissViewLoad();
                                    mApp.setBeanPrefernce(Preferences.LOCAL.USERLOGIN, response);

                                    iChange.change();

                                } else {

                                    //没绑定
                                    showMessage(message);
                                    showDialog(platform);
                                    dismissViewLoad();
                                }

                            }

                            @Override
                            public void onError(Object tag, Throwable e) {
                                dismissViewLoad();
                            }

                            @Override
                            public void onCancel(Object tag, Throwable e) {
                                dismissViewLoad();
                            }
                        });
            }

            @Override
            public void onError(Platform platform, int i, java.lang.Throwable throwable) {

                showMessage("发生未知错误");
                dismissViewLoad();

            }

            @Override
            public void onCancel(Platform platform, int i) {

                showMessage("取消第三方登录");
                dismissViewLoad();

            }
        });

        plat.showUser(null);
    }

    private void initUserInfo() {

        String LOGINTYPE = mApp.getPreference(Preferences.LOCAL.LOGINTYPE);
        userBean = mApp.getBeanPrefernce(Preferences.LOCAL.USERLOGIN);

        switch (LOGINTYPE) {

            case "1":

                if (userBean.avatar.length() > 0) {

                    Picasso.with(mContext).load(userBean.avatar).
                            placeholder(R.drawable.default120).
                            error(R.drawable.default120).
                            fit().centerCrop().
                            into(cimg_avater);

                    Picasso.with(mContext).load(userBean.avatar).
                            placeholder(R.drawable.default120).
                            error(R.drawable.default120).
                            fit().centerCrop().
                            into(cimg_draw_avater);

                }

                tv_name.setText(userBean.nickname.length() > 0 ? userBean.nickname : "uid" + userBean.uid);
                tv_draw_name.setText(userBean.nickname);

                tv_sign.setText(userBean.sign);
                tv_draw_sign.setText(userBean.sign);

                break;

            case "2":


                Picasso.with(mContext).load(userBean.qq_avatar).
                        placeholder(R.drawable.default120).
                        error(R.drawable.default120).
                        fit().centerCrop().
                        into(cimg_avater);

                Picasso.with(mContext).load(userBean.qq_avatar).
                        placeholder(R.drawable.default120).
                        error(R.drawable.default120).
                        fit().centerCrop().
                        into(cimg_draw_avater);

                tv_name.setText(userBean.qq_nick);
                tv_draw_name.setText(userBean.qq_nick);

                tv_sign.setText(userBean.sign);
                tv_draw_sign.setText(userBean.sign);

                break;

            case "3":

                Picasso.with(mContext).load(userBean.wx_avatar).
                        placeholder(R.drawable.default120).
                        error(R.drawable.default120).
                        fit().centerCrop().
                        into(cimg_avater);

                Picasso.with(mContext).load(userBean.wx_avatar).
                        placeholder(R.drawable.default120).
                        error(R.drawable.default120).
                        fit().centerCrop().
                        into(cimg_draw_avater);

                tv_name.setText(userBean.wx_nick);
                tv_draw_name.setText(userBean.wx_nick);

                tv_sign.setText(userBean.sign);
                tv_draw_sign.setText(userBean.sign);

                break;

        }
    }

    @Override
    protected void initData() {

        if (login) {

            new api(mContext).userInfo(userBean.token, userInfoCallBack);

            tv_vesion.setText("APP版本:" + getVerName());

            xmlList = new ArrayList<>();
            draw_list = new ArrayList<>();

           // xmlList.add(new HomeSec(mContext.getString(R.string.language), R.drawable.language));
            xmlList.add(new HomeSec(mContext.getString(R.string.hotel_ollection), R.drawable.collection));
            xmlList.add(new HomeSec(mContext.getString(R.string.orderquery), R.drawable.order));
            xmlList.add(new HomeSec(mContext.getString(R.string.ardbag), R.drawable.coupon));
            xmlList.add(new HomeSec(mContext.getString(R.string.contact), R.drawable.contact));
            xmlList.add(new HomeSec(mContext.getString(R.string.userfeedback), R.drawable.feedback));
            xmlList.add(new HomeSec(mContext.getString(R.string.shared_friend), R.drawable.problem));
            xmlList.add(new HomeSec(mContext.getString(R.string.common_problem), R.drawable.shared));

            draw_list.add(mContext.getString(R.string.count_setting));
            draw_list.add(mContext.getString(R.string.aboutlohas));
            draw_list.add(mContext.getString(R.string.Disclaimer));
            draw_list.add(mContext.getString(R.string.cleancache));

            CommonAdapter adapter = new CommonAdapter<HomeSec>(mContext, xmlList, R.layout.item_my_home) {
                @Override
                public void convert(ViewHolder helper, HomeSec item, int position) {

                    helper.setImageResource(R.id.img_icon, item.image);

                    helper.setText(R.id.tv_title, item.name);

                }
            };

            CommonAdapter drawAdapter = new CommonAdapter<String>(mContext, draw_list, R.layout.item_drawlayout) {
                @Override
                public void convert(ViewHolder helper, String item, int position) {
                    helper.setText(R.id.tv_title, item);
                }
            };

            lv_my.setAdapter(adapter);
            lv_draw_content.setAdapter(drawAdapter);

            lv_my.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    Intent intent;

                    switch (position) {

                       /* case 0:

                            intent = new Intent(mContext, LanActivity.class);

                            startActivity(intent);

                            break;*/

                        case 0:

                            intent = new Intent(mContext, CollectionActivity.class);

                            startActivity(intent);

                            break;

                        case 1:

                            intent = new Intent(mContext, OrderActivity.class);

                            startActivity(intent);

                            break;

                        case 2:

                            //卡券包
                            intent = new Intent(mContext, EmpActivity.class);

                            startActivity(intent);
                            break;

                        case 3:

                            showMyDialog("提示", "拨打乐活客服电话?", "确定", "取消", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                    dialog.dismiss();

                                    ArrayList permission = new ArrayList<>();

                                    permission.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);

                                    checkMyPermission(permission, new PermissionListener() {
                                        @Override
                                        public void onGranted() {
                                            callPhone(mContext.getString(R.string.lohastel));
                                        }

                                        @Override
                                        public void hasPermission() {
                                            callPhone(mContext.getString(R.string.lohastel));
                                        }

                                        @Override
                                        public void onDenied(List<Integer> deniedPermission) {
                                            //权限请求失败

                                            String denPermission;

                                            if (deniedPermission.size() > 0) {

                                                denPermission = "拨打电话权限获取失败";

                                                showMyDialog("权限请求失败", denPermission, "申请权限", null, new View.OnClickListener() {
                                                    @Override
                                                    public void onClick(View v) {

                                                        dialog.dismiss();
                                                        startActivity(getAppDetailSettingIntent());
                                                    }
                                                });
                                            }
                                        }
                                    });

                                }
                            });

                            break;

                        case 4:

                            intent = new Intent(mContext, FeedbackActivity.class);
                            startActivity(intent);

                            break;

                        case 5:

                            intent = new Intent(mContext, SharedActivity.class);
                            startActivity(intent);

                            break;

                        case 6:

                            intent = new Intent(mContext, QuestionListActivity.class);
                            startActivity(intent);

                            break;

                    }
                }
            });

            lv_draw_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent;

                    switch (position) {
                        case 0:

                            intent = new Intent(mContext, AccountActivity.class);

                            startActivity(intent);

                            break;

                        case 1:

                            intent = new Intent(mContext, AboutLohasActivity.class);

                            startActivity(intent);

                            break;

                        case 2:

                            intent = new Intent(mContext, DestActivity.class);

                            startActivity(intent);

                            break;

                        case 3:

                            try {
                                showMyDialog("清理缓存", "共有" + DataCleanManager.getTotalCacheSize(mContext)
                                        + "缓存，是否清除？", "确定", "取消", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                        DataCleanManager.clearAllCache(mContext);
                                        System.gc();
                                        showMessage("清理完成");
                                    }
                                });

                            } catch (Exception e) {
                                e.printStackTrace();
                                showMessage("清理失败");
                            }

                            break;
                    }
                }
            });

        }
    }

    @Override
    protected void initView() {

    }

    private RxResultCallback loginCallBack = new RxResultCallback<UserBean>() {
        @Override
        public void onNext(Object tag, int code, String message, UserBean response) {
            if (code == 200) {

                showMessage(message);
                dismissViewLoad();
                mApp.setBeanPrefernce(Preferences.LOCAL.USERLOGIN, response);
                mApp.setPreference(Preferences.LOCAL.LOGINTYPE, "1");
                iChange.change();

            } else {

                showMessage(message);
                dismissViewLoad();

            }
        }

        @Override
        public void onError(Object tag, Throwable e) {

            showMessage("登录失败");
            dismissViewLoad();

        }

        @Override
        public void onCancel(Object tag, Throwable e) {

        }
    };

    private RxResultCallback userInfoCallBack = new RxResultCallback<UserBean>() {
        @Override
        public void onNext(Object tag, int code, String message, UserBean response) {

            if (code == 200) {

                String token = userBean.token;
                response.token = token;
                mApp.setBeanPrefernce(Preferences.LOCAL.USERLOGIN, response);

                initUserInfo();
            }

        }

        @Override
        public void onError(Object tag, Throwable e) {

        }

        @Override
        public void onCancel(Object tag, Throwable e) {

        }
    };

    public Intent getAppDetailSettingIntent() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        localIntent.setData(Uri.fromParts("package", mContext.getPackageName(), null));

        return localIntent;
    }


    public void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        startActivity(intent);
    }

    public String getVerName() {
        String verName = "";
        try {
            verName = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

    /**
     * 显示跳转的动画
     */
    public void showViewLoad() {
        FragmentTransaction ft = getChildFragmentManager().beginTransaction();

        Fragment prev = getChildFragmentManager().findFragmentByTag("loadview");

        if (prev != null) {
            ft.remove(prev);
        }
        ft.addToBackStack(null);

        loadingFragment = new progressDialogFragment(mContext);

        loadingFragment.show(ft, "loadview");
    }

    public void dismissViewLoad() {
        if (loadingFragment != null) {

            loadingFragment.dismiss(isResumed);
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        isResumed = true;
    }

    @Override
    public void onStop() {
        super.onStop();
        isResumed = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (timer != null) {
            timer.cancel();
        }
    }

    private void showDialog(final Platform platform) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.my_dialog, null);
        final AlertDialog mDialog = new AlertDialog.Builder(mContext)
                .setView(view).create();

        mDialog.setCancelable(false);

        final EditText ed_tel = view.findViewById(R.id.ed_tel);
        final EditText ed_pwd = view.findViewById(R.id.ed_pwd);

        final Button btn_send = view.findViewById(R.id.btn_send);

        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (ed_tel.getText().toString().trim().length() < 11) {

                    showMessage("请输入正确的手机号");

                } else {

                    new api(mContext).sendCode(ed_tel.getText().toString().trim(), "login", new RxStringCallback() {
                        @Override
                        public void onNext(Object tag, String response) {
                            respon result = new Gson().fromJson(response, new TypeToken<respon>() {
                            }.getType());

                            if (result.code.equals("200")) {

                                timer = new myCountTimer(60000, 1000, btn_send);
                                timer.start();

                                showMessage("验证码以发送到您手机上");

                            } else {

                                showMessage("失败");

                            }
                        }

                        @Override
                        public void onError(Object tag, Throwable e) {

                        }

                        @Override
                        public void onCancel(Object tag, Throwable e) {

                        }
                    });
                }
            }
        });


        view.findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String number = ed_tel.getText().toString().trim();
                String pwd = ed_pwd.getText().toString().trim();

                if (ed_tel.getText().toString().trim().length() < 11) {

                    showMessage("请输入正确的手机号");

                } else if (ed_pwd.getText().toString().trim().length() == 0) {

                    showMessage("请输入正确的验证码");

                } else {

                    showViewLoad();
                    new api(mContext).loginThird(platform.getDb().getUserId(), type, platform.getDb().getUserName(),
                            platform.getDb().getUserIcon(), "", number, pwd, new RxResultCallback<UserBean>() {
                                @Override
                                public void onNext(Object tag, int code, String message, UserBean response) {

                                    //已绑定
                                    if (code == 200) {

                                        showMessage(message);
                                        dismissViewLoad();
                                        mApp.setBeanPrefernce(Preferences.LOCAL.USERLOGIN, response);
                                        iChange.change();
                                        mDialog.dismiss();

                                    } else {

                                        showMessage(message);
                                        dismissViewLoad();

                                    }
                                }

                                @Override
                                public void onError(Object tag, Throwable e) {
                                    dismissViewLoad();
                                    showMessage("服务器出错");
                                }

                                @Override
                                public void onCancel(Object tag, Throwable e) {
                                    dismissViewLoad();
                                    showMessage("服务器出错");
                                }
                            });
                }
            }
        });

        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                showMessage("登录失败");
                mDialog.dismiss();
            }
        });
        mDialog.show();
    }


    public static class myCountTimer extends CountDownTimer {

        private Button btn;

        public myCountTimer(long millisInFuture, long countDownInterval, Button btn) {
            super(millisInFuture, countDownInterval);
            this.btn = btn;
        }

        @Override
        public void onTick(long millisUntilFinished) {
            btn.setEnabled(false);
            btn.setText(millisUntilFinished / 1000 + "秒后可重发");

        }

        @Override
        public void onFinish() {
            btn.setEnabled(true);
            btn.setText("发送验证码");
        }
    }
}
